<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hash数据持久化</title>
</head>

<body>
  <div id="title">
    <button data-url="/music">音乐</button>
    <button data-url="/movie">电影</button>
    <button data-url="/news">新闻</button>
  </div>
  <div id="view">
  </div>
  <script>
    //获取按钮与视图dom元素
    const oBtns = document.querySelectorAll('#title button')
    const oView = document.getElementById("view")
    //创建路由表
    const routes = [{
      path: "/music", content: "晚风微雨问海棠"
    }, {
      path: "/movie", content: "加勒比海盗3：世界尽头"
    }, {
      path: "/news", content: "外交部召见美国驻华大使"
    },

    ]
    //遍历按钮，绑定点击事件
    for (let i = 0; i < oBtns.length; i++) {
      oBtns[i].onclick = function () {
        //每当按钮触发便把自定义属性里存的地址给到哈希地址
        location.hash = this.dataset.url
      }
    }
    //绑定window的事件，每当hash地址变化的时候执行该回调函数
    window.onhashchange = function (e) {
      //通过事件对象拿到新的地址
      const newHash = e.newURL.split("#")[1]
      //用的新的地址去路由表里找对应的组件
      routes.forEach(route => {
        if (route.path === newHash) {
          //将内容添加
          oView.textContent = route.content
        }
      })
    }

  </script>
</body>

</html>